package 生产者消费者;


/**
 * @author dexi.che on 2021/7/25  10:06 上午
 */
public class SolutionOne {
    public static Object lock = new Object();
    public static final Integer FULL = 5;
    public static volatile Integer count = 0;

    static class Producer implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                try {
                    synchronized (lock) {
                        while (count == FULL) {
                            lock.wait();
                        }
                        count++;
                        System.out.println(Thread.currentThread().getName() + " ： producer ：" + count);
                        lock.notifyAll();
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {

                }
            }
        }
    }

    static class Consumer implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                try {
                    synchronized (lock) {
                        while (count == 0) {
                            lock.wait();
                        }
                        count--;
                        System.out.println(Thread.currentThread().getName() + " ： consumer ：" + count);
                        lock.notifyAll();
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {

                }
            }
        }
    }

    public static void main(String[] args) {
        new Thread(new Producer()).start();
        new Thread(new Consumer()).start();
    }
}
